<?php
/**
 * 把打卡机中的数据导入考勤记录中
 *@author coldarmy
 * */
apf_require_class('Oa_Job_Attendance_Abstract');
class Oa_Job_Attendance_SyncCardMachineData extends Oa_Job_Attendance_Abstract {

    /** 指定文件路径 **/
    private $fpath = 'http://192.168.1.230/';
    /** 不同办公地点的门禁文件夹 menjin:陆家嘴 youyou:由由**/
    private $office = array(
            'menjin',
            'youyou',
            'bj',//北京
            'cd',//成都
            'tj',//天津
            'dl',//大连
            'sz',//深圳
            'cq' //重庆
            );
    /** 考勤系统读 **/
    private $readdb = "attendance_slave";
    /** 考勤系统写 **/
    private $writedb = "attendance_master";

    private $date = '';

    public function run($params = 0){
        $this->log("开始准备导入数据...");
        if(empty($this->office)) {
            $this->log('没有任何办公室的打卡文件');
            exit;
        }
        foreach ($this->office as $val) {
            $data = $this->fetch_data_from_txt($params,$val.'/');
        }
        $this->log("数据导入完毕");
    }
    /**
     * 如果非工作日，结束Job
     */
    private function _is_work_day() {
        apf_require_class('Tools_Tools');
        $workday = Tools_Tools::get_instance()->actual_work_day_by_month_list(date('Ym'));
        $day = date('Ymd');
        if (in_array($day, $workday)) {
            return true;
        } else {
            $this->log("今天非工作日，无需提醒!");
            return false;
        }
    }
    private function _send_error_email($file,$index){
        if(!$this->_is_work_day()){
            return;
        }
        $error_log = '/tmp/not_found_kq_file'.date('Y-m-d').'.txt';
        if(!file_exists($error_log)){
             file_put_contents($error_log,1);
        }else{
            $error_num = file_get_contents($error_log);
            $error_num = intval($error_num)+1;
            file_put_contents($error_log,$error_num);
        }
        if($error_num ==10){//send_mail
            file_put_contents($error_log,0);
            apf_require_class('Tools_SendMail');
            $content = "没有找到".$file."打卡记录";
            $acc_list = array(
                    'bj'=>'jlchen@anjuke.com',
                    'cd'=>'michelleteng@anjuke.com',
                    'tj'=>'paulgao@anjuke.com',
                    'dl'=>'jiaojiaowang@anjuke.com',
                    'sz'=>'tingyanglv@anjuke.com',
                    'cq'=>'jxie@anjuke.com',
                    'sugz'=>'yujunwang@anjuke.com'
            );
            $mail = empty($acc_list[$index]) ? 'andycao@anjuke.com' :$acc_list[$index] ;
            Tools_SendMail::get_instance()->send($mail,'注意城市打卡机异常==='.date('Y-m-d H:i'),$content);
        }
    }
    /**
     * 从打卡产生的数据日志中读取打卡详细信息
     *
     * @access private
     * @return array()
     */
    private function fetch_data_from_txt($params,$val) {
        $result = array();
        $filename = date('Ymd');
        if($params && $params > 0 && $params < 99999999 ) {
            $filename = $params;
        }
        $this->date = $filename;
        $filetype = '.Txt';
        $file = $this->fpath.$val.$filename.$filetype;
        /*if(!file_exists($file)) {
            return $result;
        }*/
        $content = file_get_contents($file);
        if(empty($content)) {
            $this->log('文件不存在');
            $this->_send_error_email($file,$val);
        }
        $data = explode("\n",$content);
        if(empty($data)) {
            return $result;
        }
        $tmp = array();
        foreach ($data as $key => $val) {
            $temp = explode(" ",$val);
            $tp['code'] = trim($temp[4]);
            $tp['access_date'] = $temp[0];
            if(strlen($tp['access_date']) < 7) {
                $tp['access_date'] = $this->date;
            }
            $tp['access_time'] = $temp[1];
            $tp['machine_num'] = '11-01';
            $tp['updated'] = time();
            /** 写入数据 **/
            $this->insert_data_to_all_record($tp);
            /** 判断当前第一打卡时间，第一天最后一次打卡时间 **/
            $this->insert_data_to_day_record($tp);
        }
    }

    /**
     * 数据写入到打卡记录表中
     *
     * @param mixed $data
     * @access private
     * @return void
     */
    private function insert_data_to_all_record($data) {
        $result = '';
        if(empty($data) || empty($data['code'])) {
            return $result;
        }
        $q = "SELECT id FROM access_all_record WHERE code = '{$data['code']}' AND access_date = '{$data['access_date']}' AND access_time = '{$data['access_time']}'";
        $b = $this->get_db_row($q,$this->writedb );
        if(isset($b['id'])) {
            return $result;
        }
        $sql = "INSERT INTO access_all_record(code,access_date,access_time,machine_num,updated) VALUE(?,?,?,?,?)";
        $result = $this->execute($sql, array($data['code'],$data['access_date'],$data['access_time'],$data['machine_num'],$data['updated']), $this->writedb);
        return $result;
    }

    private function insert_data_to_day_record($data) {
        $result = '';
        if(empty($data)) {
            return $result;
        }
        $code = $data['code'];
        $user_id = $this->get_user_id_by_code($data['code']);
        if(empty($user_id)) {
            $this->log("该员工号没有对应的数据:{$code}");
            return $result;
        }
        $nowdate = $data['access_date'];
        //检查当天是否已有打开记录
        $q = "SELECT * FROM access_day_record WHERE user_id = $user_id AND access_date = '{$nowdate}'";
        $tmp = $this->get_db_row($q,$this->writedb,array());
        //如无当天数据新插入数据
        if(!isset($tmp['id'])) {
            $i = "INSERT INTO access_day_record(access_date,start_work,user_id,created) VALUE(?,?,?,?)";
            $result = $this->execute($i, array($nowdate,$data['access_time'],$user_id,time()),$this->writedb);
            $this->log("用户ID:".$user_id."数据新写入");
        } else {
            //下次打卡需大于上次
            if($data['access_time'] > $tmp['end_work']) {
                $id = $tmp['id'];
                $now = time();
                $u = "UPDATE access_day_record SET end_work = '{$data['access_time']}',updated = $now WHERE id = $id";
                $result =  $this->execute($u, array(),$this->writedb);
                $this->log("用户ID:".$user_id."数据更新");
            } elseif($data['access_time'] < $tmp['start_work']) {
                $id = $tmp['id'];
                $now = time();
                $u = "UPDATE access_day_record SET start_work = '{$data['access_time']}',updated = $now WHERE id = $id";
                $result =  $this->execute($u, array(),$this->writedb);
                $this->log("用户ID:".$user_id."数据更新");
            } else {
                $this->log("用户ID:".$user_id."无数据处理");
            }
        }
        return $result;
    }

    private function get_user_id_by_code($code) {
        $result = array();
        if(empty($code)) {
            return $result;
        }
        $code = strtoupper($code);
        $sql = "SELECT user_id FROM user_info WHERE code = '{$code}'";
        $tmp = $this->get_db_row($sql,$this->writedb,array());
        if($tmp) {
            $result = $tmp['user_id'];
        }
        return $result;

    }
}
